#coding=utf-8
'''
Created on 2017-7-13

@author: sandy
'''

from twisted.internet.protocol import ReconnectingClientFactory
from twisted.internet import reactor
import Const
import logging
import TBaseProtocol
import LogServerParse
import LogServerBuild
import RemoteManager

class LogServerFactory(ReconnectingClientFactory):
    def __init__(self):
        ReconnectingClientFactory.maxDelay = 5
    
    def buildProtocol(self, addr):
        logging.info(u"LogServerFactory buildProtocol!!!")
        self.resetDelay()
        return instance
    
    def startedConnecting(self, connector):
        logging.info(u"LogServerFactory startedConnecting!!!")
    
    def clientConnectionLost(self, connector, reason):
        logging.warn(u"LogServerFactory clientConnectionLost!!!")
        ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
        
    def clientConnectionFailed(self, connector, reason):
        logging.warn(u"LogServerFactory clientConnectionFailed!!!")
        ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)

class LogSrv(TBaseProtocol.TBaseProtocol):
                      
    def __init__(self):
        TBaseProtocol.TBaseProtocol.__init__(self)
    
    def start(self, ip, port):
        reactor.connectTCP(ip,port,LogServerFactory())
        
    def stop(self):
        pass
    
    def connectionMade(self):
        logging.info(u"LogSrv connectionMade()")
        TBaseProtocol.TBaseProtocol.reset(self)
        self.sendPacket(LogServerBuild.login(RemoteManager.instance.sid))
        
    def packetReceived(self, cmd, pkt):
        try:
            LogServerParse.parse(self, cmd, pkt)
        except Exception:
            logging.exception(u"LogServerParse.parse(), cmd=%d" % cmd)

    def saveLog(self,uid,msgtype,msg):
        self.sendPacket(LogServerBuild.saveData(uid,msgtype,msg))

instance = LogSrv()

if __name__ == '__main__':
    pass